<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/8 0008
 * Time: 10:24
 */

namespace app\api\controller\v1;


use app\currency\service\AccessTokenService;
use app\wechat\service\WechatService;
use library\Controller;
use library\tools\Data;
use think\Db;
use think\facade\Cache;

class Login extends Controller
{
    /**
     * 登陆入口
     * $_GET['code'] 必传
     * @param $id
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function read($id)
    {
        $id = strtolower($id);//所有转换为小写
        if(!in_array($id,['member','cleaner','agent']))
        {
            throw new \think\Exception("client {$id} not found");
        }
        $pid = $this->request->get('pid',0);
        is_numeric($pid) || $pid = 0;//如果不为数字则设为0
        $agent_id = $this->request->get('agent_id',0);
        is_numeric($agent_id) || $agent_id = 0;
        $scene = $this->request->get('scene','');//reg
        $code = $this->request->get('code');
        if(empty($code)) $this->error("code不能为空");

        $result = $this->_getSessionKey($code);
        //获取到微信登陆信息存入数据库
        if($id != 'member' && ($pid == 0 && $agent_id == 0 && $scene == ''))
        {
            //无法自动注册
            if(!Db::name(ucfirst($id))->where('openid',$result['openid'])->find())
            {
                $this->error('登陆失败！');
            }
        }
        $member_data = [
            'openid' => $result['openid'],
            'nickname' => $result['nickname'],
            'headimg' => $result['headimg']
        ];
        Data::save(ucfirst($id),$member_data,'openid');


        //开始登陆生成token
        $member = Db::name(ucfirst($id))->where('openid',$result['openid'])
            ->field('openid',true)
            ->find();
        if($member['status'] != '1')
        {
            $this->error('账户已被禁用，请联系管理员！');
        }
        if($member['pid'] == '0' && $pid > 0 && $id !== 'agent')
        {
            $member['pid'] = $pid;
            Db::name(ucfirst($id))->where('openid',$result['openid'])->setField('pid',$pid);
            //保洁员邀请新用户赠送积分赠送次数
            if($id == 'cleaner' && !empty(sysconf('invite_present_switch'))){
                Db::name('Cleaner')->where('id',$pid)->setInc('integral_present_num',1);
            }
        }
        if($id === 'cleaner' && $member['agent_id'] == '0' && $agent_id > 0)
        {
            $member['agent_id'] = $agent_id;
            Db::name(ucfirst($id))->where('openid',$result['openid'])->setField('agent_id',$agent_id);
        }
        //查询用户是否绑定手机号
        $code = 1;
        if($member['phone'] == ''){
            $code = 202;
        }
        $token = AccessTokenService::createAccessToken($member['id'],$id);
        $this->success('微信授权登陆成功！', array_merge($token,['member' => $member]),$code);
    }

    private function _getSessionKey(string $code): array
    {
        $cache = Cache::get($code, []);
        if (isset($cache['openid'])) {
            return $cache;
        }
        $wechat = WechatService::WeChatOauth();
        if(($token = $wechat->getOauthAccessToken()) && isset($token['openid'])){
            $fansinfo = $wechat->getUserInfo($token['access_token'], $token['openid']);
            if(!empty($fansinfo)) {
                $token['nickname'] = $fansinfo['nickname'];
                $token['headimg'] = $fansinfo['headimgurl'];
                Cache::set($code, $token, 60);
                return $token;
            }

        }
        $this->error("登录失败");
    }
}